<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>历史订单</span>
      </div>
    </template>
    
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="已退房订单" name="checkout">
        <el-table :data="checkoutOrders" stripe style="width: 100%">
          <el-table-column prop="id" label="订单ID" width="100"/>
          <el-table-column prop="userId" label="用户ID" width="120"/>
          <el-table-column prop="hotelName" label="酒店名称"/>
          <el-table-column prop="roomType" label="房型"/>
          <el-table-column prop="amount" label="金额" width="100"/>
          <el-table-column prop="paymentMethod" label="支付方式" width="100"/>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="支付时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.payTime) }}
            </template>
          </el-table-column>
          <el-table-column label="退房时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.checkoutTime || row.checkout_time) }}
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <el-tab-pane label="已取消订单" name="cancel">
        <el-table :data="cancelOrders" stripe style="width: 100%">
          <el-table-column prop="id" label="订单ID" width="100"/>
          <el-table-column prop="userId" label="用户ID" width="120"/>
          <el-table-column prop="hotelName" label="酒店名称"/>
          <el-table-column prop="roomType" label="房型"/>
          <el-table-column prop="amount" label="金额" width="100"/>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="取消时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.cancelTime) }}
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="totalOrders"/>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getOrderList } from '@/api/order'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'

const userInfoStore = useUserInfoStore()
const tableData = ref([])
const activeTab = ref('checkout')
const pageIndex = ref(1)
const pageSize = ref(20)

// 计算属性：已退房订单
const checkoutOrders = computed(() => {
  return tableData.value.filter((order: any) => 
    order.payTime && (order.checkoutTime || order.checkout_time) && !order.cancelTime
  )
})

// 计算属性：已取消订单
const cancelOrders = computed(() => {
  return tableData.value.filter((order: any) => order.cancelTime)
})

// 计算属性：当前选项卡的订单总数
const totalOrders = computed(() => {
  return activeTab.value === 'checkout' ? checkoutOrders.value.length : cancelOrders.value.length
})

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 加载所有订单数据
const initData = () => {
  // 确保当前用户是管理员
  if (!userInfoStore.isAdmin()) {
    ElMessage.error('您没有权限访问此页面')
    return
  }
  
  getOrderList().then(res => {
    console.log('获取所有订单响应:', res)
    
    const result = res.data
    if (result && result.code === 200) {
      // 直接使用后端返回的数据
      tableData.value = Array.isArray(result.data) ? result.data : []
      
      // 处理字段名称差异
      tableData.value = tableData.value.map(item => {
        // 确保数据一致性，处理可能的checkoutTime/checkout_time命名差异
        if (item && item.checkout_time && !item.checkoutTime) {
          item.checkoutTime = item.checkout_time
        }
        return item
      })
      
      console.log('已退房订单数:', checkoutOrders.value.length)
      console.log('已取消订单数:', cancelOrders.value.length)
    } else {
      console.error('获取订单列表失败:', result)
      ElMessage.error(result?.msg || '获取订单列表失败')
    }
  }).catch(error => {
    console.error('获取订单列表错误:', error)
    ElMessage.error('网络错误，获取订单列表失败')
  })
}

const handleTabClick = () => {
  // 切换选项卡时重置分页
  pageIndex.value = 1
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
}

const handleCurrentChange = (index: number) => {
  pageIndex.value = index
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}
.pagination-box { 
  padding-top: 16px; 
  display: flex; 
  justify-content: right; 
}
</style> 